<?php

function auth_redirect()
{
	global $session;
	if (!$session->is_set('author_id'))
	{
		$location = $_SERVER['REQUEST_URI'];
		header('Location: index.php?redirect_url=' . $location);
	}
}

function authenticate($username, $password)
{
	global $session, $db, $authors_table;
	
	$s = "SELECT * FROM $authors_table WHERE username = '$username'";
	$r = $db->get_result($s);
		
	if ($r != null)
	{
		$expected_password = encrypt_password($password, $r[0]['password_salt']);
		if ($expected_password == $r[0]['password_hash'])
		{
			return $r[0]['id'];
		}
	}
	return null;
}

function get_author()
{
	global $session, $db, $authors_table;
	
	if (!$session->is_set('author_id'))
		return null;
		
	$id = $session->get('author_id');
	$s = "SELECT * FROM $authors_table WHERE id = $id";
	$q = $db->get_result($s);
	
	if ($q != null)
	{
		return $q[0];
	}
	return null;
}

function encrypt_password($password, $salt)
{
	$str = $password + $salt;
	$hash = hash("md5", $str);
	return $hash;
}

function generate_salt()
{
	return hash("md5", rand());
}


?>